package com.cdck.safe.dete.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdck.safe.dete.common.util.SecurityUtils;
import com.cdck.safe.dete.model.entity.*;
import com.cdck.safe.dete.mapper.BookRecordMapper;
import com.cdck.safe.dete.model.query.BaseKeywordsQuery;
import com.cdck.safe.dete.model.vo.BookRecordVO;
import com.cdck.safe.dete.model.vo.MyBookRecordVO;
import com.cdck.safe.dete.security.userdetails.SysUserDetails;
import com.cdck.safe.dete.service.*;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (BookRecord)表服务实现类
 *
 * @author wp
 * @since 2024-02-25 16:48:35
 */
@Service
@RequiredArgsConstructor
public class BookRecordServiceImpl extends ServiceImpl<BookRecordMapper, BookRecord> implements BookRecordService {

    @Resource
    private SysUserService userService;

    @Resource
    private LaboratoryService laboratoryService;

    @Resource
    private BookingService bookingService;

    @Resource
    private SeatService seatService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BookRecord getBookRecordFormData(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     * <p>
     * queryParams 筛选条件
     *
     * @return 查询结果
     */
    @Override
    public IPage<BookRecordVO> queryByPage(BaseKeywordsQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        List<Long> bookIds = new ArrayList<>();
        if (StrUtil.isNotBlank(keywords)) {
            //用户姓名
            LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.like(SysUser::getNickname, keywords);
            List<SysUser> sysUserList = userService.list(userWrapper);
            List<Long> userIds = sysUserList.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (userIds.size() > 0) {
                LambdaQueryWrapper<Booking> bookWrapper = new LambdaQueryWrapper<>();
                bookWrapper.in(Booking::getUserId, userIds);
                List<Booking> bookingList = bookingService.list(bookWrapper);
                bookIds = bookingList.stream().map(item -> item.getId()).collect(Collectors.toList());
            }

            //实验室编号 或者用户的预约
            LambdaQueryWrapper<Laboratory> labWrapper = new LambdaQueryWrapper<>();
            labWrapper.like(Laboratory::getLabNo, keywords);
            List<Laboratory> laboratoryList = laboratoryService.list(labWrapper);
            List<Long> labIds = laboratoryList.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (labIds.size() > 0) {
                LambdaQueryWrapper<Booking> bookWrapper2 = new LambdaQueryWrapper<>();
                bookWrapper2.in(labIds.size() > 0, Booking::getLabId, labIds);
                List<Booking> bookingList2 = bookingService.list(bookWrapper2);
                List<Long> bookIds2 = bookingList2.stream().map(item -> item.getId()).collect(Collectors.toList());
                bookIds.addAll(bookIds2);
            }
        }
        Page<BookRecordVO> pageVO = new Page<>(pageNum, pageSize);
        //如果bookIds的size为0 返回空
        if (StrUtil.isNotBlank(keywords) && bookIds.size() == 0) {
            return pageVO;
        }

        Page<BookRecord> page = new Page<>(pageNum, pageSize);
        Page<BookRecord> recordPage = this.page(
                page,
                new LambdaQueryWrapper<BookRecord>()
                        .in(StrUtil.isNotBlank(keywords) && bookIds.size() > 0, BookRecord::getBookId, bookIds)
        );
        List<BookRecord> records = recordPage.getRecords();
        List<BookRecordVO> recordsVo = records.stream().map(item -> {
            BookRecordVO vo = new BookRecordVO();
            BeanUtils.copyProperties(item, vo);
            Long bookId = item.getBookId();
            Booking booking = bookingService.getById(bookId);
            BeanUtils.copyProperties(booking, vo, "id");
            Laboratory laboratory = laboratoryService.getById(booking.getLabId());
            vo.setLabName(laboratory.getName());
            SysUser sysUser = userService.getById(booking.getUserId());
            vo.setBookUser(sysUser.getNickname());
            Seat seat = seatService.getById(booking.getSeatId());
            vo.setSeatNo(seat.getSeatNo());
            return vo;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(recordPage, pageVO, "record");
        pageVO.setRecords(recordsVo);
        return pageVO;

    }

    /**
     * 新增数据
     *
     * @param bookRecord 实例对象
     * @return 实例对象
     */
    @Override
    public boolean saveBookRecord(BookRecord bookRecord) {
        return this.save(bookRecord);
    }

    /**
     * 修改数据
     *
     * @param bookRecord 实例对象
     * @return 实例对象
     */
    @Override
    public boolean updateBookRecord(Long id, BookRecord bookRecord) {
        return this.updateById(bookRecord);
    }

    /**
     * 通过主键删除数据
     *
     * @param idsStr ids集合
     * @return 是否成功
     */
    @Override
    public boolean deleteBookRecords(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(ids);
    }

    @Override
    public List<MyBookRecordVO> myBookRecord(Long labId) {
        SysUserDetails user = SecurityUtils.getUser();
        Long userId = user.getUserId();
        LambdaQueryWrapper<Booking> bookWrapper = new LambdaQueryWrapper<>();
        bookWrapper.eq(Booking::getUserId, userId);
        bookWrapper.eq(labId != null && labId > 0, Booking::getLabId, labId);
        List<Booking> bookingList = bookingService.list(bookWrapper);

        List<MyBookRecordVO> voList = bookingList.stream().map(item -> {
            MyBookRecordVO myBookRecordVO = BeanUtil.copyProperties(item, MyBookRecordVO.class);
            Laboratory laboratory = laboratoryService.getById(item.getLabId());
            myBookRecordVO.setLabName(laboratory.getName());
            Seat seat = seatService.getById(item.getSeatId());
            myBookRecordVO.setSeatNo(seat.getSeatNo());
            myBookRecordVO.setStartTime(item.getBookStartTime());
            myBookRecordVO.setEndTime(item.getBookEndTime());
            myBookRecordVO.setBookId(item.getId());
            myBookRecordVO.setBookUser(user.getUsername());
            if (item.getStatus() == 3) {
                LambdaQueryWrapper<BookRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
                recordQueryWrapper.eq(BookRecord::getBookId, item.getId());
                BookRecord one = this.getOne(recordQueryWrapper);
                myBookRecordVO.setRealEndTime(one.getRealEndTime());
            }
            return myBookRecordVO;
        }).collect(Collectors.toList());

        return voList;
    }
}
